﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Bzure.Common.Data;
using Bzure.Common.Core;

namespace Bzure.Common.Configuration.AppConfiguration
{
    public static class ConfigTemplateSource
    {
        static ConfigTemplateSource()
        {
            Name = System.Configuration.ConfigurationManager.AppSettings["ConfigTemplateProviderName"];
        }
        public static string Name { get; set; }
    }
    public class AutoID
    {
        int max;
        int Length;
        int Count = 0;

        public string Header { get; private set; }
        public string MasterID { get; set; }
        public int MasterIDLenght { get; private set; }
        public string Key { get; private set; }
        public event EventHandler OnCountReset;
        public AutoID(string key, int MaxValue, string header, int masteridLength)
        {
            MasterIDLenght = masteridLength;
            Header = header;
            Key = key;
            max = MaxValue;
            Length = MaxValue.ToString().Length;
        }
        public string Get(int spacer)
        {
            lock (this)
            {
                Count += spacer;
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < Length; i++)
                    sb.Append("0");
                sb.Append(Count.ToString());
                string s = sb.ToString().Substring(sb.Length - Length, Length);
                string oldMasterID = this.MasterID;
                if (Count > max - 1)
                {
                    if (OnCountReset != null)
                        this.OnCountReset(this, null);
                    Count = 0 - spacer;//归零
                }
                return string.Format("{0}{1}{2}", this.Header, oldMasterID, s);
            }
        }
        public string Get()
        {
            return this.Get(1);
        }
    }


    public static class IDGenerator
    {

        public const string TemplateKey = "IDGENERATORTEMPLATEKEY";

        static Dictionary<string, AutoID> IDBuilders = new Dictionary<string, AutoID>();

        static ConfigTemplateModel ConfigTemplateModel;
        static IDGenerator()
        {

            IConfigTemplate ConfigTemplate = ConfigTemplateModel.GetConfigTemplate(TemplateKey);
            if (ConfigTemplate == default(IConfigTemplate))
            {
                ConfigTemplateModel = new ConfigTemplateModel(TemplateKey);
                ConfigTemplateModel.Save();
            }
            else
            {
                ConfigTemplateModel = new ConfigTemplateModel(ConfigTemplate);
            }
            ConfigTemplateModel.OnConfigTemplateUpdated += new ConfigTemplateModel.UpdateConfigTemplateHanlder(ConfigTemplateModel_OnConfigTemplatedUpdated);
        }

        static void ConfigTemplateModel_OnConfigTemplatedUpdated(IConfigTemplate Template, string ConfigKey, string ConfigValue)
        {

        }
        static string GenerateMasterID(string ConfigKey, int Length)
        {
            KeyValuePair<string, string> kvp = ConfigTemplateModel.Configurations.FirstOrDefault(m => m.Key == ConfigKey);
            int value = string.IsNullOrEmpty(kvp.Key) || string.IsNullOrEmpty(kvp.Value) ? 1 : int.Parse(kvp.Value) + 1;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < Length; i++)
                sb.Append("0");
            sb.Append(value.ToString());
            string s = sb.ToString().Substring(sb.Length - Length, Length);
            ConfigTemplateModel.AppendConfig(ConfigKey, value.ToString());
            return s;
        }

        public static string GenerateID(string ConfigKey, int MaxValue, string Header, int MasterIDLenght)
        {
            AutoID autoid;
            if (!IDBuilders.TryGetValue(ConfigKey, out autoid))
            {
                autoid = new AutoID(ConfigKey, MaxValue, Header, MasterIDLenght);
                IDBuilders[ConfigKey] = autoid;
                autoid.OnCountReset += new EventHandler(autoid_OnCountReset);
                autoid.MasterID = GenerateMasterID(ConfigKey, MasterIDLenght);
            }
            return autoid.Get();
        }

        static void autoid_OnCountReset(object sender, EventArgs e)
        {
            AutoID autoid = sender as AutoID;
            autoid.MasterID = GenerateMasterID(autoid.Key, autoid.MasterIDLenght);
        }
    }
}
